package org.ws.kardex.model;

import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import com.google.appengine.api.datastore.Key;
import java.util.LinkedList;
import java.util.List;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import org.ws.kardex.gae.PMF;

/**
 *
 * @author Gerardino
 */
@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class Inventory {

    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Key id;

    @Persistent
    private String owner;
    
    @Persistent
    private List<String> users = new LinkedList<String>();

    @Persistent
    private String name;
    
    @Persistent(mappedBy="i")
    private List<Product> products = new LinkedList<Product>();

    public Inventory(String name){
        this.name = name;
    }

    public Key getId(){
        return this.id;
    }
    public void setName(String name){
        this.name = name;
    }
    public String getName(){
        return this.name;
    }
    public void setOwner(String owner){
        this.owner = owner;
    }
    public String getOwner(){
        return this.owner;
    }
    public List<Product> getProduct(){
        return this.products;
    }
    /*
     * Lists the users as in the Google App Engine User class .toString() value
     */
    public List<String> getUsers(){
        return this.users;
    }
    public void setUsers(List<String> users){
        this.users = users;
    }
    public void setProduct(List<Product> products){
        this.products.clear();
        this.products.addAll(products);
    }
    
    
    public static List<Inventory> getInventoriesByUser(String user){
        PersistenceManager pm = PMF.pm;
        
        List<Inventory> inventories = new LinkedList<Inventory>();
        if (user != null){
            Query q = pm.newQuery(Inventory.class);
            q.setFilter("owner == p_user");
            q.declareParameters("String p_user");
            
            inventories.addAll((List<Inventory>)q.execute(user));
            
            
            /*
             * This seems rather ugly, but it has its reasons.
             * If I try a filter condition with both expresions, the App Engine
             * gives an ugly error about the lack of a feature.
             * I think the feature is that you can't compare to attributes on
             * the same filter. So, while it gets fixed, I'll be using this
             */
            q.setFilter("users.contains(p_user)");
            inventories.addAll((List<Inventory>)q.execute(user));
        }
        
        return inventories;
    }

}
